package org.csu.bbs.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.csu.bbs.entity.Likes;
import org.csu.bbs.persistence.LikesMapper;
import org.csu.bbs.result.BetterResult;
import org.csu.bbs.service.LikesService;
import org.csu.bbs.service.PostsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class LikesServiceImpl implements LikesService {
    @Autowired
    LikesMapper likesMapper;

    @Autowired
    PostsService postService;

    @Override
    public BetterResult<Boolean> IsLike(String uid, int pid) {
        Integer likes = 0;
        try{
            QueryWrapper<Likes> likesQueryWrapper = new QueryWrapper<>();
            likesQueryWrapper.eq("userid", uid)
                             .eq("postid", pid);
            likes = likesMapper.selectCount(likesQueryWrapper);
            return new BetterResult<>(likes == 1, 200);
        } catch (Exception e) {
            e.printStackTrace();
            return new BetterResult<>(likes == 1, 401);
        }
    }

    @Override
    public BetterResult<Integer> addOrDeleteLikes(String uid, int pid) {
        try{
            QueryWrapper<Likes> likesQueryWrapper = new QueryWrapper<>();
            likesQueryWrapper.eq("userid", uid)
                             .eq("postid", pid);
            Integer likes = likesMapper.selectCount(likesQueryWrapper);
            if (likes == 0){
                likesMapper.insert(new Likes(uid, pid));
            }
            else{
                likesMapper.delete(likesQueryWrapper);
            }
            return postService.LikePost(pid, likes == 0);
        } catch (Exception e){
            e.printStackTrace();
            return new BetterResult<>(0, 500);
        }
    }
}
